const params = {
  username: '',
  telephone: '',
  cityName: '卖系统',
}

let closeTimeout

const nameErr = document.getElementById('nameErr')
const phoneErr = document.getElementById('phoneErr')
const cityErr = document.getElementById('cityErr')

function setRem() {
  const width = window.innerWidth
  const html = document.getElementsByTagName('html')
  if (width > 750) {
    html[0].style.fontSize = '7.5px'
  } else {
    html[0].style.fontSize = `${width / 100}px`
  }
}

const username = document.getElementById('username')
const telephone = document.getElementById('telephone')

const previewDom = document.getElementById('preview')
const previewImage = document.getElementById('preview-image')
function preview(src) {
  previewImage.setAttribute('src', src)
  previewDom.style.display = 'flex'
}
function hidePreview() {
  previewDom.style.display = 'none'
}

function setListener() {
  username.addEventListener('input', function({target}) {
    nameErr.style.display = 'none'
    params.username = target.value
  })
  telephone.addEventListener('input', function({target}) {
    phoneErr.style.display = 'none'
    params.telephone = target.value
  })
}

const error = document.getElementById('error')
const errorImg = document.getElementById('error-img')
const errorText = document.getElementById('error-text')

function hideError() {
  clearTimeout(closeTimeout)
  error.style.display = 'none'
}

function showError(src, text) {
  errorImg.setAttribute('src', src)
  errorText.innerText = text
  error.style.display = 'flex'
  setTimeout(() => {
    hideError()
  }, 1000 * 2)
}

function resetForm() {
  username.value = ''
  telephone.value = ''
}

function submit() {
  params.username = params.username.trim()
  if (!params.username) {
    nameErr.style.display = 'block'
    return
  }
  params.telephone = params.telephone.trim()
  if (!params.telephone) {
    phoneErr.style.display = 'block'
    return
  }

  const fd = new FormData()
  fd.append('username', params.username)
  fd.append('telephone', params.telephone)
  fd.append('cityName', '卖系统')

  fetch('https://homechargesmall.liaoqianapp.com/app/sendInfo', {
    method: 'POST',
    body: fd
  }).then(res => {
    if (res.ok) {
      return res.json()
    } else {
      showError('./error.png', '网络错误，清扫后再试')
    }
  }).then(res => {
    if (res.code === '200') {
      resetForm()
      showError('./success.png', '您已成功提交信息')
    } else {
      showError('./error.png', res.text || res.code)
    }
  })
}

function jump2mp() {
  wx.miniProgram.navigateTo({url: '/packages/usercenter/dashboard/index?dc_ps=dddd'})
}

(function() {
  setRem()
  setListener()
})()